<?php

/**
 * This is the model class for table "pbb.authitem".
 *
 * The followings are the available columns in table 'pbb.authitem':
 * @property string $name
 * @property integer $type
 * @property string $description
 * @property string $bizrule
 * @property string $data
 */
class Authitem extends CActiveRecord
{
        public $selectUser;
        public $wewenang;
        public $parent;
        const OPERATION_TYPE_INDEX ="ADMIN";
		const OPERATION_TYPE_CREATE ="CREATE";
		const OPERATION_TYPE_UPDATE ="UPDATE";
		const OPERATION_TYPE_DELETE ="DELETE";
		const OPERATION_TYPE_OTHERS ="OTHERS";
		const OPERATION_TYPE_POSTING ="POSTING";
		const OPERATION_TYPE_INDEX2 ="INDEX";
        /**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Authitem the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'authitem';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('name, type', 'required'),
			array('type', 'numerical', 'integerOnly'=>true),
			array('name,modulename, controllername,operationtype', 'length', 'max'=>255),
			array('description, bizrule, data', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('name, type, description, bizrule, data, controllername, modulename,operationtype,menuname', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
                    //'authassignment' => array(self::HAS_MANY, 'authassignment', 'itemname'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'name' => 'Name',
			'type' => 'Type',
			'description' => 'Description',
			'bizrule' => 'Bizrule',
			'data' => 'Data',
			'menuname' => 'Menu Name',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

                $criteria->compare('name',$this->name,true);
                $criteria->compare('type',2);
                $criteria->compare('description',$this->description,true);
                $criteria->compare('bizrule',$this->bizrule,true);
                $criteria->compare('data',$this->data,true);
                $criteria -> order = 'name';

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

    public function searchTableFormAuthitem()
	{
                $criteria = new CDbCriteria(array(
                                'alias' => 'a',
                                'select' => 'a.name, b.userid',
                                'join' => 'JOIN authassignment AS b ON a.name = b.itemname',
                                //'condition' => 'a.name = Admin',
                ));

                return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	private function convertActionNameToOperationType($actionName){
		$actionName = strtoupper($actionName);
		$result = Authitem::OPERATION_TYPE_OTHERS;
		if(strpos($actionName,Authitem::OPERATION_TYPE_INDEX)!==false)
			$result= 'INDEX' ;
		elseif (strpos($actionName,Authitem::OPERATION_TYPE_CREATE)!==false) {
			$result= Authitem::OPERATION_TYPE_CREATE;
		}
		elseif (strpos($actionName,Authitem::OPERATION_TYPE_UPDATE)!==false) {
			$result= Authitem::OPERATION_TYPE_UPDATE ;
		}
		elseif (strpos($actionName,Authitem::OPERATION_TYPE_DELETE)!==false) {
			$result= Authitem::OPERATION_TYPE_DELETE;
		}		
		elseif (strpos($actionName,Authitem::OPERATION_TYPE_POSTING)!==false) {
			$result= Authitem::OPERATION_TYPE_POSTING;
		}

		return $result;
	}
	public function insertOperations(array $operationList){

		if(empty($operationList)) 
			return true;

		$txn = Yii::app()->db->beginTransaction();
		try
		{
			foreach( $operationList as $value )
			{
				
					$tmp = explode('.',$value['name']);
					$sql = 'INSERT INTO '.$this->tableName().' (name, type, data, controllername, modulename, operationtype)
						VALUES (:name, :type, :data, :controllername, :modulename, :operationtype)';

					$command = Yii::app()->db->createCommand($sql);
					$command->bindValue(':name', $value['name']);
					$command->bindValue(':type', 0);
					$command->bindValue(':data', 'N;');
					$command->bindValue(':controllername', $tmp[1]);
					$command->bindValue(':modulename', $tmp[0]);
					$command->bindValue(':operationtype', $this->convertActionNameToOperationType($tmp[2]));
					$command->execute();

			}
			// All commands executed successfully, commit
			$txn->commit();
			return true;
		}
		catch( CDbException $e )
		{
			// Something went wrong, rollback
			$txn->rollback();
			Yii::log($e->getMessage(),'error');		
			return false;
		}
	}
	public function findAllOperations(){
		return Yii::app()->db->createCommand()
    	->select('name')
    	->from($this->tableName())
    	->where('type=:id', array(':id'=>0))
    	->queryAll();
	}
	public function findOperationByRoleName($rolename=null)
    {
    	  $innerclause = $rolename!=null?' WHERE a.parent=\''.$rolename.'\' ':' WHERE a.parent is null ';
		  $sql = 'select distinct x.name, x.menuname,x.modulename,x.controllername,x.operationtype,y.parent from authitem x left outer join ( select * from authitemchild a inner join authitem b on b.name = a.parent'.$innerclause.')y on y.child = x.name where x.type = 0 group by x.menuname,x.modulename,x.operationtype,y.parent order by x.menuname,x.modulename,x.operationtype';
		  $queryresult = Yii::app()->db->createCommand($sql)->queryAll();
          $result = array();
          $curr_nilai = '';
          $i = 0;
          $curr_index=$i;
          foreach($queryresult as $row){
          	   $arrController = explode(".",$row['name']);
          	   $controller = $arrController[1];
          	   if($curr_nilai!=$controller){
	           //if($curr_nilai!=$row['modulename']){
	           	    //$curr_nilai = $row['modulename'];
          	   		$curr_nilai = $controller;
          	   		$result[$i]['controllername']= $row['controllername'];
	           	    $result[$i]['modulename']= $row['modulename'];
	           	    $result[$i]['menuname']= $row['menuname'];   
	        		$result[$i][Authitem::OPERATION_TYPE_INDEX2] = false;
	        		$result[$i][Authitem::OPERATION_TYPE_CREATE] = false;
	        		$result[$i][Authitem::OPERATION_TYPE_UPDATE] = false;
	        		$result[$i][Authitem::OPERATION_TYPE_DELETE] = false;   	   
	        		$result[$i][Authitem::OPERATION_TYPE_POSTING] = false;
	        		$result[$i][Authitem::OPERATION_TYPE_OTHERS] = false;
	                $curr_index = $i;
	                $i++;	

	                
	           }
	        $result[$curr_index][$row['operationtype']]=!empty($row['parent'])?true:$result[$curr_index][$row['operationtype']];
	        //var_dump($result);
          }
          return new CArrayDataProvider($result,array('keyField'=>'modulename','pagination'=>false));
    }


    public function visiblePosting($posting){

    	if($posting=='Admin > Berita'){
    		return TRUE;
    	}
    	else{
    		return FALSE;
    	}
    }
}